package cn.wad.web.servlet;

import cn.wad.doman.User;
import cn.wad.service.UserSevice;
import cn.wad.service.impl.ImplUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/jsonServlet")
public class JsonServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应的数据格式为json
        System.out.println("jsonServlet.....");
        response.setContentType("application/json;charset=utf-8");
        //获取username
        String username = request.getParameter("username");
        System.out.println("username::"+username);
        //2.调用service层判断用户名是否存在
        Map<String, String[]> map = request.getParameterMap();
        System.out.println("map::"+map);
        User user = new User();
        try {
            BeanUtils.populate(user , map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserSevice sevice = new ImplUserService();
        user = sevice.findByUsernaem(user);
        System.out.println("user:::"+user);

        Map<String , Object> omap = new HashMap<String, Object>();
        //期望服务器响应回的数据格式：{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
        //                         {"userExsit":false,"msg":"用户名可用"}

        if (username.equals(user)){

            //存在
            omap.put("userExsit",true);
            omap.put("msg","此用户名太受欢迎,请更换一个");
        }else {

            //不存在
            omap.put("userExsit",false);
            omap.put("msg","用户名可用");
        }

        //转化json对象
        ObjectMapper mapper = new ObjectMapper();

        mapper.writeValue(response.getWriter(),omap);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
